package com.roc.web.action.unPay;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.UnPay;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.service.unPay.IUnPayService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Namespace("/unpay")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class UnPayAction extends PaginationBaseAction {
	
	private static Logger logger = Logger.getLogger(UnPayAction.class);
	private UnPaySearchCondition searchCondition;
	private UnPay unPay;
	private InputStream excelFile;
	
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IUnPayService unPayService;
	@Autowired
	private IExcelService excelService;
	
	/**
	 * 初始化直连商户管理页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = {
			@Result(name = "success", location = "/pages/unPay/unPayMana.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String init() throws Exception {
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())) {
			return SUCCESS;
		}
		
		addActionError("无权限访问!!!");
		return ERROR;
	}
	
	/**
	 * 查询操作
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryUnpay", results = {
			@Result(name = "success", location = "/pages/unPay/unPayMana.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String queryUnpay() throws Exception {
		try {
			if (searchCondition == null) {
				searchCondition = (UnPaySearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new UnPaySearchCondition();
				}
			}
			int rows = pagenitionService.countSQL(searchCondition);
			
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);
				
				List<UnPay> list = new ArrayList<UnPay>();
				if(null != searchRsList && searchRsList.size()>0){
					Iterator<?> it = searchRsList.iterator();
					
					while(it.hasNext()){
						Object[] obj = (Object[]) it.next();
						UnPay up = new UnPay();
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

						DecimalFormat df = new DecimalFormat("#.##");
						
						String feeT1 = Constance.Null2EmptyTrim(obj[3]);
						String feeT1Top = Constance.Null2EmptyTrim(obj[4]);
						String feeT0 = Constance.Null2EmptyTrim(obj[5]);
						feeT1 = df.format(new BigDecimal(feeT1).multiply(new BigDecimal(100))); 
						feeT1Top = df.format(new BigDecimal(feeT1Top)); //.divide(new BigDecimal(100))
						feeT0 = df.format(new BigDecimal(feeT0).multiply(new BigDecimal(100))); 
						
						up.setId(Long.parseLong(Constance.Null2EmptyTrim(obj[0])));
						up.setMerchantNo(Constance.Null2EmptyTrim(obj[1]));
						up.setTerminalNo(Constance.Null2EmptyTrim(obj[2]));
						up.setFeeT1(feeT1.toString());
						up.setFeeT1Top(feeT1Top.toString());
						up.setFeeT0(feeT0.toString());
						up.setAccountNo(Constance.Null2EmptyTrim(obj[6]));
						up.setAccountName(Constance.Null2EmptyTrim(obj[7]));
						up.setBankName(Constance.Null2EmptyTrim(obj[8]));
						up.setBankCode(Constance.Null2EmptyTrim(obj[9]));
						up.setYlId(Constance.Null2EmptyTrim(obj[10]));
						up.setAddTime(sdf.parse(Constance.Null2EmptyTrim(obj[11])));
						up.setOper(Constance.Null2EmptyTrim(obj[12]));
						up.setRemark(Constance.Null2EmptyTrim(obj[13]));
						
						list.add(up);
					}
					
					searchRsList.clear();
					searchRsList.addAll(list);
					
				}
			}
			if (searchRsList.size() == 0) {
				getRequest().setAttribute("msge", "查询银联直连商户为空");
			}
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
			
		}
		return SUCCESS;
	}
	
	/**
	 * 初始化添加直连商户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "addInit", results = {
			@Result(name = "success", location = "/pages/unPay/addUnpay.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String addInit() {
		logger.info("初始化直连商户信息添加页面~");
		Map<String, String> bMap = ConfigProperties.getSysDB1("UP_BC_CD",false);
		getRequest().setAttribute("bMapToList", bMap.values());//银行信息
		return SUCCESS;
	}
	
	/**
	 * 添加直连商户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "addUnpay", results = {
			@Result(name = "success", location = "/pages/unPay/unPayMana.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String addUnpay() {
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		try {
			int count = unPayService.add(unPay, op);
			if (count > 0) {
				addActionMessage("添加成功!");
			}
		} catch (ServiceException e) {
			addActionError("添加直连商户失败!");
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 初始化修改直连商户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "updateInit", results = {
			@Result(name = "success", location = "/pages/unPay/updateUnpay.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String updateInit() {
		logger.info("初始化直连商户信息修改页面~");
		Map<String, String> bMap = ConfigProperties.getSysDB1("UP_BC_CD",false);
		getRequest().setAttribute("bMapToList", bMap.values());//银行信息
		
		try {
			unPay = unPayService.update(unPay);
		} catch (ServiceException e) {
			addActionError("修改直连商户失败!");
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	/**
	 * 修改银联直连商户信息
	 * 
	 * @return
	 */
	@Action(value = "updateUnpay", results = {
			@Result(name = "success", location = "/pages/unPay/unPayMana.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String updateUnpay() {
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			int count = unPayService.updateUnPay(unPay, op);
			if (count > 0) {
				addActionMessage("修改成功~");
			}
		} catch (ServiceException e) {
			addActionError("修改银联直连商户信息失败~");
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 删除银联直连商户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "deleteInit", results = {
			@Result(name = "success", location = "/pages/unPay/unPayMana.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String deleteInit() {
		
		try {
			int count  = unPayService.delete(unPay);
			if (count > 0) {
				addActionMessage("删除成功~");
			}
		} catch (ServiceException e) {
			addActionError("删除直连商户失败!");
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	/**
	 * 直连商户报表导出
	 * @return
	 * @throws Exception
	 */
	@Action(value = "exportInit", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xlsx", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String exportInit() throws Exception {
		try {
			if (searchCondition == null) {
				searchCondition = (UnPaySearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new UnPaySearchCondition();
				}
			}
			int rows = pagenitionService.countSQL(searchCondition);
			
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);
				
				List<UnPay> list = new ArrayList<UnPay>();
				if(null != searchRsList && searchRsList.size()>0){
					Iterator<?> it = searchRsList.iterator();
					
					while(it.hasNext()){
						Object[] obj = (Object[]) it.next();
						UnPay up = new UnPay();
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
						
						up.setId(Long.parseLong(Constance.Null2EmptyTrim(obj[0])));
						up.setMerchantNo(Constance.Null2EmptyTrim(obj[1]));
						up.setTerminalNo(Constance.Null2EmptyTrim(obj[2]));
						up.setFeeT1(Constance.Null2EmptyTrim(obj[3]));
						up.setFeeT1Top(Constance.Null2EmptyTrim(obj[4]));
						up.setFeeT0(Constance.Null2EmptyTrim(obj[5]));
						up.setAccountNo(Constance.Null2EmptyTrim(obj[6]));
						up.setAccountName(Constance.Null2EmptyTrim(obj[7]));
						up.setBankName(Constance.Null2EmptyTrim(obj[8]));
						up.setBankCode(Constance.Null2EmptyTrim(obj[9]));
						up.setYlId(Constance.Null2EmptyTrim(obj[10]));
						up.setAddTime(sdf.parse(Constance.Null2EmptyTrim(obj[11])));
						up.setOper(Constance.Null2EmptyTrim(obj[12]));
						up.setRemark(Constance.Null2EmptyTrim(obj[13]));
						
						list.add(up);
					}
					
					searchRsList.clear();
					searchRsList.addAll(list);
					
				}
				logger.info("开始导出直连商户信息~");
				SXSSFWorkbook work = excelService.exportUnpay(list);

				ByteArrayOutputStream output = new ByteArrayOutputStream();
				work.write(output);

				byte[] ba = output.toByteArray();
				excelFile = new ByteArrayInputStream(ba);
				output.flush();
				output.close();
				logger.info("导出直连商户信息成功~");
				
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
			
		}
		
		return SUCCESS;
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_UNPAY_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_FREEZE_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		
		return Constance.PAGE_MAX_SIZE + "";
	}

	public UnPaySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(UnPaySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public UnPay getUnPay() {
		return unPay;
	}

	public void setUnPay(UnPay unPay) {
		this.unPay = unPay;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		String excelName = "银联直连商户信息" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;
	}
	
}
